package com.intgrt.manager.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.intgrt.manager.entity.SysRole;
import com.intgrt.manager.midentity.CombTree;
import com.intgrt.manager.service.SysRoleService;
import com.intgrt.manager.service.base.impl.BaseServiceImpl;
import com.intgrt.manager.util.ProjectConstants;
import com.intgrt.manager.util.ProjectTools;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl implements SysRoleService {

	@Override
	public String getList(SysRole entity) {
		String content = "s.id,s.orgid,s.rolename,s.crttm,g.orgname";
		String cdtsql = "sys_role s left join sys_organize g on s.orgid = g.id where s.orgid = "+entity.getOrgid();
		return getPageDate(content, cdtsql, entity.getPage(), entity.getRows()).toJSONString();
	}

	@Override
	public String saveEntity(SysRole entity) {
		String sql = "insert into sys_role (orgid,rolename,crttm) values ("
				+ entity.getOrgid()+",'"+entity.getRolename()+"',"+ProjectTools.curTime()+")";
		return this.execute(sql)+"";
	}

	@Override
	public String editEntity(SysRole entity) {
		String sql = "update sys_role set rolename = '"+entity.getRolename()+"' where id = "+entity.getId();
		return this.execute(sql)+"";
	}

	@Override
	public String delEntity(String roleid) {
		String sql = "sys_user where roleid = "+roleid;
		long num = this.getCount(sql);
		if(num>0){
			return "2";
		}
		List<String> sqllst = new ArrayList<String>();
		sqllst.add("delete from sys_auth where roleid = "+roleid);
		sqllst.add("delete from sys_role where id = "+roleid);
		try {
			this.batch(sqllst);
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "1";
		}
		
	}
	
	public String saveAuth(String roleid, String nodes){
		//1#2#-1,1#3,1#3#-1,1#3#5,1#3#6,1#3#7,1#4,1#4#-1,1#4#8,1#4#9,1#4#10,1#4#17,1#5,1#5#-1,1#5#11,1#5#12,1#5#13
		List<String> sqllst = new ArrayList<String>();
		sqllst.add("delete from sys_auth where roleid = "+roleid);
		if(ProjectTools.isNotEmpty(nodes)){
			Set<String> mset = new HashSet<String>();
			Map<String,String> btnmap = new HashMap<String,String>();
			String[] mary = nodes.split(",");
			for(int i=0;i<mary.length;i++){
				String[] smary = mary[i].split(ProjectConstants.AUTH_SEPARATOR);
				if(3==smary.length){
					if(!mset.contains(smary[0])&&!"0".equals(smary[0])){
						mset.add(smary[0]);
					}
					if(btnmap.containsKey(smary[1])){
						btnmap.put(smary[1], btnmap.get(smary[1])+","+smary[2]);
					}else{
						btnmap.put(smary[1], ","+smary[2]);
					}
				}
			}
			for(String pm:mset){
				sqllst.add("insert into sys_auth (roleid,menuid,buttons) values ("+roleid+","+pm+",'')");
			}
			for(Entry<String,String> entry:btnmap.entrySet()){
				String btns = entry.getValue().replace(",-1", "");
				if(ProjectTools.isNotEmpty(btns)){
					btns = btns.substring(1);
				}
				sqllst.add("insert into sys_auth (roleid,menuid,buttons) values ("+roleid+","
						+entry.getKey()+",'"+btns+"')");
			}
		}
		try {
			this.batch(sqllst);
			return "0";
		} catch (Exception e) {
			e.printStackTrace();
			return "1";
		}
	}

	@Override
	public JSONArray getAuthTree(int roleid) {
		//返回权限树的内容
		JSONArray resja = new JSONArray();
		//二级菜单
		Map<String,JSONArray> secmap = new HashMap<String,JSONArray>();
		//菜单按钮
		Map<String,JSONArray> btnmap = new HashMap<String,JSONArray>();
		//遍历菜单时区分上下级
		List<String> idlst = new ArrayList<String>();
		if(0==roleid){//超级管理员角色
			this.tidyMenuBtns(btnmap, null);
			//整理菜单数据
			String sql = "select id,parentid,menuname from sys_menu where id > 1 order by parentid,id";
			List<Map<String,Object>> reslst = this.getMapList(sql);
			for(Map<String,Object> resmap:reslst){
				JSONObject jo = new JSONObject();
				String menuid = String.valueOf(resmap.get("id"));
				String pmid = String.valueOf(resmap.get("parentid"));
				String menuname = String.valueOf(resmap.get("menuname"));
				idlst.add(menuid);
				if(idlst.contains(pmid)){
					jo.put("id", pmid+ProjectConstants.AUTH_SEPARATOR+menuid);
					jo.put("text", menuname);
					if(btnmap.containsKey(menuid)){
						jo.put("children", btnmap.get(menuid));
					}else{
						JSONArray ja = new JSONArray();
						JSONObject jo1 = new JSONObject();
						jo1.put("id", pmid+ProjectConstants.AUTH_SEPARATOR+menuid+
								ProjectConstants.AUTH_SEPARATOR+"-1");
						jo1.put("text", "无");
						ja.add(jo1);
						jo.put("children", ja);
					}
					if(secmap.containsKey(pmid)){
						secmap.get(pmid).add(jo);
					}else{
						JSONArray ja = new JSONArray();
						ja.add(jo);
						secmap.put(pmid, ja);
					}
				}else{
					jo.put("id", menuid);
					jo.put("text", menuname);
					jo.put("children", new JSONArray());
					resja.add(jo);
				}
			}
		}else{//其他角色
			StringBuilder btnids = new StringBuilder();
			String sql = "select a.menuid,a.buttons,b.parentid,b.menuname from sys_auth a "
					+ "left join sys_menu b on a.menuid = b.id where a.roleid = "+roleid+" order by b.parentid,b.id";
			List<Map<String,Object>> reslst = this.getMapList(sql);
			
			for(Map<String,Object> resmap:reslst){
				JSONObject jo = new JSONObject();
				String menuid = String.valueOf(resmap.get("menuid"));
				String btnid = String.valueOf(resmap.get("buttons"));
				if(ProjectTools.isNotEmpty(btnid)){
					btnids.append(","+btnid);
				}
				String pmid = String.valueOf(resmap.get("parentid"));
				String menuname = String.valueOf(resmap.get("menuname"));
				idlst.add(menuid);
				if(idlst.contains(pmid)){
					jo.put("id", pmid+ProjectConstants.AUTH_SEPARATOR+menuid);
					jo.put("text", menuname);
					if(secmap.containsKey(pmid)){
						secmap.get(pmid).add(jo);
					}else{
						JSONArray ja = new JSONArray();
						ja.add(jo);
						secmap.put(pmid, ja);
					}
				}else{
					jo.put("id", menuid);
					jo.put("text", menuname);
					jo.put("children", new JSONArray());
					resja.add(jo);
				}
			}
			if(btnids.length()>1){
				this.tidyMenuBtns(btnmap, btnids.substring(1));
			}
			
			for(Entry<String,JSONArray> entry:secmap.entrySet()){
				JSONArray ja = entry.getValue();
				for(int i=0;i<ja.size();i++){
					JSONObject jo = ja.getJSONObject(i);
					String[] sec = jo.getString("id").split(ProjectConstants.AUTH_SEPARATOR);
					if(btnmap.containsKey(sec[1])){
						ja.getJSONObject(i).put("children", btnmap.get(sec[1]));
					}else{
						JSONArray ja1 = new JSONArray();
						JSONObject jo1 = new JSONObject();
						jo1.put("id", jo.getString("id")+ProjectConstants.AUTH_SEPARATOR+"-1");
						jo1.put("text", "无");
						ja1.add(jo1);
						ja.getJSONObject(i).put("children", ja1);
					}
				}
				
			}
		}
		for(int i=0;i<resja.size();i++){
			String menuid = resja.getJSONObject(i).getString("id");
			if(secmap.containsKey(menuid)){
				resja.getJSONObject(i).put("children", secmap.get(menuid));
			}
		}
		return resja;
	}

	@Override
	public List<String> roleAuth(String roleid) {
		List<String> list = new ArrayList<String>();
		String sql = "select a.menuid,a.buttons,b.parentid from sys_auth a "
				+ "left join sys_menu b on a.menuid = b.id where a.roleid = "+roleid;
		List<Map<String,Object>> reslst = this.getMapList(sql);
		if(reslst.size()>0){
			for(Map<String,Object> resmap:reslst){
				String menuid = String.valueOf(resmap.get("menuid"));
				String btns = String.valueOf(resmap.get("buttons"));
				String parentid = String.valueOf(resmap.get("parentid"));
				if(ProjectTools.isNotEmpty(btns)){
					String[] btnAry = btns.split(",");
					for(int i=0;i<btnAry.length;i++){
						list.add(parentid+ProjectConstants.AUTH_SEPARATOR
								+menuid+ProjectConstants.AUTH_SEPARATOR+btnAry[i]);
					}
				}else{
					list.add(parentid+ProjectConstants.AUTH_SEPARATOR+menuid+ProjectConstants.AUTH_SEPARATOR+"-1");
				}
			}
		}
		return list;
	}
	
	@Override
	public List<CombTree> getCombTree(String pid, String orgid) {
		String sql = "";
		List<CombTree> comblst = new ArrayList<CombTree>();
		if(ProjectTools.isEmpty(pid)){
			sql = "select id, rolename from sys_role where orgid = "+orgid;
			List<Map<String, Object>> reslst =  this.getMapList(sql);
			if(reslst.size()>0){
				for(Map<String, Object> map:reslst){
					CombTree org = new CombTree(String.valueOf(map.get("id")), String.valueOf(map.get("rolename")));
					comblst.add(org);
				}
			}
		}
		return comblst;
	}
	
	private void tidyMenuBtns(Map<String,JSONArray> btnmap, String btnids){
		String sql = "select a.id,a.menuid,a.btnname,b.parentid from sys_menu_btn a "
				+ " left join sys_menu b on a.menuid = b.id ";
		if(null!=btnids){
			sql += "where a.id in ("+btnids+") ";
		}
		sql += "order by a.menuid, a.btnorder";
		List<Map<String,Object>> reslst = this.getMapList(sql);
		//整理菜单按钮数据
		for(Map<String,Object> resmap:reslst){
			JSONObject jo = new JSONObject();
			String menuid = String.valueOf(resmap.get("menuid"));
			String parentid = String.valueOf(resmap.get("parentid"));
			String btnid = parentid+ProjectConstants.AUTH_SEPARATOR+menuid+
					ProjectConstants.AUTH_SEPARATOR+resmap.get("id");
			String btnname = String.valueOf(resmap.get("btnname"));
			jo.put("id", btnid);
			jo.put("text", btnname);
			if(btnmap.containsKey(menuid)){
				btnmap.get(menuid).add(jo);
			}else{
				JSONArray ja = new JSONArray();
				JSONObject jo1 = new JSONObject();
				jo1.put("id", parentid+ProjectConstants.AUTH_SEPARATOR+menuid+
						ProjectConstants.AUTH_SEPARATOR+"-1");
				jo1.put("text", "无");
				ja.add(jo1);
				ja.add(jo);
				btnmap.put(menuid, ja);
			}
		}
	}

}